
using System.Collections;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Pool;
using UnityEngine.UI;

public class GameUI : MonoBehaviour
{

    [SerializeField] Image TopBackImage;
    [SerializeField] Image ScoreImage;
    [SerializeField] Image PauseImage;

    [SerializeField] RectTransform pannel;
    [SerializeField] RectTransform bg;

    [SerializeField] private Camera mainCamera;

    [SerializeField] private Text timeLabel;
    [SerializeField] private Text levelLabel;
    [SerializeField] private Text scoreLabel;

    [SerializeField]private Pop pop;

    private Canvas gameUICanvas;

    [SerializeField]private GameObject starPrefab;
    private ObjectPool<GameObject> pool;

    private int gameTotalTime = 60;

    public int GameTotalTime {
        set {
            gameTotalTime = value;
        }
        get {
            return gameTotalTime;
        }
    }

    private float frameTime = 0;

    private bool countdown = false;

    public bool Countdown {
        set {
            countdown = value;
        }
        get {
            return countdown;
        }
    }
    void Awake()
    {
        GameManager.Instance().topUI = this;
        gameUICanvas = GetComponent<Canvas>();
        Debug.Log("UIAwake");
    }

    public void ResetUI() {
        frameTime = 0;
        GameTotalTime = 60;
        // 分数
        scoreLabel.text = "0";
        levelLabel.text = "关卡: " + GameManager.Instance().levelManager.CurLevel.ToString();
        Countdown = false;
    }

    public void StartTimeCountdown() {
        Countdown = true;
    }

    public void ShowResult(bool isWin) {
        pop.gameObject.SetActive(true);
        pop.Show(EPopType.RESULT,isWin);
    }

    public void ShowPause() {
        pop.gameObject.SetActive(true);
        pop.Show(EPopType.PAUSE);
    }

    public void AdapterUICamera()
    {
        // Debug.Log();
        Debug.Log("适配UI相机");
        Debug.Log("分数显示canvas是否是主Canvas: " + gameUICanvas.isRootCanvas);
        CanvasScaler canvasScaler = gameUICanvas.GetComponent<CanvasScaler>();

        Debug.Log("uiscaleMode is " + canvasScaler.uiScaleMode);
        Debug.Log("screen match mode is " + canvasScaler.screenMatchMode);
        Debug.Log("math is " + canvasScaler.matchWidthOrHeight);
        _ = gameUICanvas.worldCamera;
        gameUICanvas.worldCamera = mainCamera;
    }

    // Start is called before the first frame update
    private void Start()
    {
        pool = new ObjectPool<GameObject>(
            createFunc: () => Instantiate(starPrefab),
            maxSize: 100,
            defaultCapacity: 30,
            actionOnGet: obj => obj.SetActive(true),
            actionOnRelease: obj => obj.SetActive(false),
            actionOnDestroy: obj => Destroy(obj)
        );

    }

    public GameObject GetStar() {
        return pool.Get();
    }

    public void ReleaseObject(GameObject obj) {
        pool.Release(obj);
    }

    /// <summary>
    /// 展示星星特效
    /// </summary>
    /// <param name="screenPos"></param>
    public IEnumerator ShowStarEffect(Vector2 screenPos,int score = 0) {
        if(screenPos == null) {
            Debug.Log("screenPos is null");
            yield return null;
        }
        int count = (int)Random.Range(1f,4f);
        for(int i = 0; i < count; i++) {
            GameObject starobject = GetStar();
            if(starobject == null) {
                starobject = Instantiate(starPrefab,screenPos,Quaternion.identity,bg);
            }
            starobject.transform.position = screenPos;
            starobject.transform.parent = bg;

            starobject.transform.DOScale(new Vector3(0.5f,0.5f,0.5f),0.2f);
            int currentIndex = i;
            // 设置星星的出生位置
            starobject.transform.DOMove(ScoreImage.rectTransform.position,0.3f).OnComplete(() => {
                ReleaseObject(starobject);
                if(currentIndex == 0) {
                    AddScoreAnim(score);
                }
            });
            yield return new WaitForSeconds(0.1f);
        }
    }

    private void AddScoreAnim(int score) {
        Debug.Log("add scoreAnim score is " + score);
        scoreLabel.text = score.ToString();

        Sequence scoreSequence = DOTween.Sequence();
        scoreSequence.Append(scoreLabel.rectTransform.DOScale(0.8f,0.1f));
        scoreSequence.AppendInterval(0.05f);
        scoreSequence.Append(scoreLabel.rectTransform.DOScale(1f,0.1f));
        scoreSequence.SetLoops(2,LoopType.Yoyo);
    }

    void OnGUI() {
        // GUIStyle buttonStyle = new GUIStyle(GUI.skin.button);
        // buttonStyle.fontSize = 40;
        // buttonStyle.normal.textColor = Color.white;

        // if(GUI.Button(new Rect(10,400,200,80),"moveTest",buttonStyle)) {
        //     Debug.Log("开始移动测试");
        //     // Invoke(nameof(MoveEvent),0.1f);
        //     AddScoreAnim(100);
        // }
    }

    private void MoveEvent() {
        Vector2 secondPos = GameManager.Instance().slotManagers.slotsPosList[1];
        GameObject starobject = GetStar();
        if(starobject == null) {
            starobject = Instantiate(starPrefab,secondPos,Quaternion.identity,bg);
        }
        starobject.transform.position = secondPos;
        starobject.transform.parent = bg;
        // 设置星星的出生位置

        RectTransform starRect = starobject.GetComponent<RectTransform>();

        RectTransformUtility.ScreenPointToLocalPointInRectangle(bg,ScoreImage.rectTransform.position,null,out Vector2 t);
        Debug.Log($"目标位置{t}");

        starobject.transform.DOScale(new Vector3(0.5f,0.5f,0.5f),0.4f);

        starobject.transform.DOMove(ScoreImage.rectTransform.position,0.5f).OnComplete(() => {
            Debug.Log("Move Complete");
            ReleaseObject(starobject);
        });
    }

    public void BtnEvents(string data)
    {
        switch (data)
        {
            case "pause":
                Debug.Log("pause");
                ShowPause();
                break;
            default:
                break;
        }
    }

    private void UpdateTimeLabel(int totalSeconds) {
        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;

        string minutesStr = minutes < 10 ? $"0{minutes}" : minutes.ToString();
        string secondsStr = seconds < 10 ? $"0{seconds}" : seconds.ToString();

        string res = minutesStr + ":" + secondsStr;
        timeLabel.text = res;
    }

    void Update() {
        if(Countdown) {
            frameTime += Time.deltaTime;
            if(frameTime >= 1) {
                frameTime = 0;
                gameTotalTime--;
                if(gameTotalTime >= 0) {
                    UpdateTimeLabel(gameTotalTime);
                } else {
                    GameManager.Instance().game.gameStatus = EGameStatus.GAMEOVER;
                }
            }
        }
    }
}
